<?php

namespace teach\service;

use Yii;

class Calculation
{
    public function add($oid, $uid, $mid, $out_trade_no)
    {
        //查找订单用户
        $order = $this->orderOne($oid, $uid, $mid, $out_trade_no);
        if (!$order) {
            return false;
        }




        //订单用户积分跟信誉累积
        $this->userScore($uid, $order['total_fee']);
        //增加积分记录
        $map = [
            'uid' => $uid,
            'fid' => $uid,
            'mid' => $mid,
            'openid' => $order['openid'],
            'score' => $order['total_fee'],
            'des' => '购买产品订单号:'. $out_trade_no,
            'create_time'=> time()
        ];
        $this->userScoreRecord($map);

        //查找分配记录
        $records = $this->billRecords($uid, $out_trade_no);

        if (!$records) {
            return false;
        }
        $WeChat = new \teach\components\WeChat();
        $SendWeChatMessage = new SendWechatMessage();
        //$redis = Yii::$app->redis;
        //给用户加入订单中记录的值返利
        $tip = "您的佣金已结算入账，请到小程序中查看";
        foreach ($records as $record) {
            //循环给目标用户加积分-可用于提取的金额
            $this->totalRed($record['uid'], $record['amount']);

            //将记录改为已结算
            $this->billUpdate($record['id']);

            //给用户发送小程序消息
            $user = $this->userOne($record['uid']);
//            while (true) {
//                $formid = $redis->rpop("formid_{$user['openid']}");
//                $status = $WeChat->sendMsg($SendWeChatMessage->getScore($user['openid'], $formid, $record['amount'],$tip));
//                if ($status['errcode'] == 0 || $formid == false) {
//                    break;
//                }
//            }
            $WeChat->send($SendWeChatMessage->getScores($user["openid"], $record["amount"], "分享成功获取",$tip));

        }
        //将pay改为2已结算
        $this->dealPay($order['p_id']);
        return true;
    }

    /**
     * 查找其中的订单
     * @param $oid
     * @param $uid
     * @param $mid
     * @param $out_trade_no
     * @return array|false
     */
    private function orderOne($oid, $uid, $mid, $out_trade_no)
    {
        $sql = "SELECT o.total_fee, o.id, o.openid, o.logistic_fee, p.id AS p_id FROM mall_order AS o LEFT JOIN mall_pay AS p ON p.out_trade_no = o.out_trade_no WHERE o.id = {$oid} AND o.uid = {$uid} AND o.mid = {$mid} AND o.out_trade_no = '{$out_trade_no}' AND p.status = 3";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 给购买者增加积分增加信誉 累计消费总额
     * @param $uid
     * @param $total_fee
     * @return int
     */
    private function userScore($uid, $total_fee)
    {
        $sql = "UPDATE edu_user SET score = score + {$total_fee}, score_total  = score_total + {$total_fee}, mall_use = mall_use + {$total_fee} WHERE id = {$uid}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 查找未结算的记录
     * @param $uid
     * @param $out_trade_no
     * @return array
     */
    private function billRecords($uid, $out_trade_no)
    {
        $sql = "SELECT * FROM mall_bill WHERE out_trade_no = '{$out_trade_no}' AND sid = {$uid} AND status = 2";
        return Yii::$app->db->createCommand($sql)->queryAll();
    }

    /**
     * 将mall_pay 改为已结算2
     * @param $p_id
     * @return int
     */
    private function dealPay($p_id)
    {
        $sql = "UPDATE mall_pay SET status = 2 WHERE id = {$p_id}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**给用户加上可领取红包的金额
     * @param $uid
     * @param $amount
     * @return int
     */
    private function totalRed($uid, $amount)
    {
        $sql = "UPDATE edu_user SET mall_total_fee = mall_total_fee + {$amount} WHERE id = {$uid}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 把记录改为已经结算
     * @param $id
     * @return int
     */
    private function billUpdate($id)
    {
        $time = time();
        $sql = "UPDATE mall_bill SET status = 1, finish_time = {$time} WHERE id = {$id}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 查找用户的openid, unionid
     * @param $uid
     * @return array|false
     */
    private function userOne($uid)
    {
        $sql = "SELECT openid, unionid FROM edu_user WHERE id = {$uid}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    private function userScoreRecord($map)
    {
        return Yii::$app->db->createCommand()->insert('mall_score_record',$map)->execute();
    }


}